/*
 * Commissiong_test.c
 *
 *  Created on: 2023年7月31日
 *      Author: fjx
 */
#include "util.h"
#include "app_log.h"
#include <stdio.h>
#include "mac/MacCrypto.h"
#include "bsp_nvm.h"
#include "device.h"
#include "device_rfmid.h"
#include "net_protocol.h"
#include "net_rolling_code.h"
#include "mac_packethandle.h"
#include "mac_timeSync.h"
#include "app_api.h"
#include "bsp_rf.h"
#include "net_msgseq.h"
#include "device_type.h"
#include "net_addressing.h"
#include "net_logout.h"
#include "device_nvm.h"
#include"mac_TDMA.h"
#include "net_register.h"
#include "net_packet.h"

#define CONFIG_AE_DE
#define CONFIG_COMMISSIONG_KEY_CRYPTO
join_t  msg={
#if defined (RFM_DEVICE)
    .rfmStatus = EN_MSG_STATUS_JOIN_NODE_PAGING_BUILD_PACKET,
#endif
};
uint8_t _key[RBF_KEY_LENGTH_MAX]={0};
NET_MESSAGE_STATUS_EN register_status = EN_MSG_STATUS_IDLE;

#if defined (DEBUG_MODE_KEY)
uint8_t _keydefault1[RBF_KEY_LENGTH_MAX] =DEFAULTKEY_1_VALUE_DEFALUT;
uint8_t _keydefault2[RBF_KEY_LENGTH_MAX] =DEFAULTKEY_2_VALUE_DEFALUT;
#if defined (HUB_DEVICE)
uint8_t _keysystem[RBF_KEY_LENGTH_MAX]=KEY_SYSTEM_DEFAULT;
uint8_t _keybroadcast[RBF_KEY_LENGTH_MAX]=KEY_BROADCAST_DEFAULT;
#endif //end of "HUB_DEVICE"
#endif //end of "DEBUG_MODE_KEY"
static uint8_t join_count = 10;
static NET_DATA_STATUS_EN net_data_s=NET_DATA_STATUS_SUCCESS;
static bool b_rfm_confirm = false;

static uint8_t rfm_id = 0;
static void set_rfm_id (uint8_t id)
{
  rfm_id = id;
}
static uint8_t get_rfm_id(void)
{
  return rfm_id;
}
static void set_b_rfm_confirm (bool status)
{
  b_rfm_confirm = status;
}
static bool get_b_rfm_confirm (void)
{
  return b_rfm_confirm;
}

NET_DATA_STATUS_EN get_net_data_status (void)
{
  NET_DATA_STATUS_EN status;
  status = net_data_s;
  net_data_s = NET_DATA_STATUS_SUCCESS;
  return status;
}
void set_net_data_status (NET_DATA_STATUS_EN status)
{
  net_data_s = status;
}
#ifdef RFM_DEVICE
static uint8_t net_get_device_type(void)
{
  uint8_t device_type=0;
  //TODO:APP接口进行替换
  getThisParam(ENbyDeviceType,&device_type);
  return device_type;//EN_DEVICE_TYPE_IO_MC;
}
static uint8_t net_get_hard_type(void)
{
  uint8_t hard_type = 0;
  //TODO:APP接口进行替换
  getThisParam(ENbyHardType,&hard_type);
  return hard_type;
}
static uint32_t net_get_rfVer(void)
{
  uint8_t pver[3];
  uint32_t rfVer;
  //TODO:APP接口进行替换
  getThisParam(ENpbyRfVer,&pver);
  rfVer = pver[0];
  rfVer <<= 8;
  rfVer |= pver[1];
  rfVer <<= 8;
  rfVer |= pver[2];
  return rfVer;
}
static uint32_t net_get_sVer(void)
{//TODO:APP接口进行替换
  uint8_t pver[3];
  uint32_t sVer=0;
  getThisParam(ENpbySensorVer,&pver);
  sVer = pver[0];
  sVer <<= 8;
  sVer |= pver[1];
  sVer <<= 8;
  sVer |= pver[2];
  return sVer;
}
static uint8_t net_get_model_type(void)
{
  //TODO:APP接口进行替换
  uint8_t type;
  getThisParam(ENbyModelType,&type);
  return type;
}
#endif
NET_MESSAGE_STATUS_EN get_register_status(void)
{
  return register_status;
}

void set_register_status(NET_MESSAGE_STATUS_EN status)
{
  register_status = status;
}
void clear_register_status(void)
{
  register_status = EN_MSG_STATUS_IDLE;
}
#if defined (HUB_DEVICE)
/*
 * return: true,  rssi在信号接受范围内或者没有RSSI限制
 *         false, rssi进行限制,并且rssi值不在接收范围内
 */
//#define CONFIG_RSSI_LIMIT
bool is_rssi_limit(int8_t rssi)
{
  uint8_t rssi_limit=0;

  getThisParam(ENbyRssiLimit,&rssi_limit);
  if(get_net_printf_log() == true){
      DS_app_log_error("RN=%d,R=%d\n",rssi_limit,rssi);
  }
//  rssi_limit=1;
#if defined (CONFIG_RSSI_LIMIT)
  if(( rssi_limit == 1 && rssi > -40)  || rssi_limit == 0){
      return true;
  }
  return false;
#else
  return true;
#endif
}
static void gateway_ack_event_packet(void)
{
  RBFMacHeader_t hdr={
      .frameCtl = RBF_VERSION,
      .srcId = 0,
      .routID = 0,
      .cmd = RBF_CMD_GATEWAY_ACK_EVENT,
      /*panId,
       *destID,  需要填充
       *rollungCode
       * */

  };
  uint8_t buf[4]={0};
  uint8_t temp8 = 0;
  uint32_t temp32 = 0;

  getThisParam(ENpbySystemID,buf);
  hdr.panId = l_get_be24(buf);


  msg.hubStatus = EN_MSG_STATUS_JOIN_CONFIRM_BUILD_PACKECT;
  hdr.destID=get_rfm_id();//msg.join_info.rfmid;

   //1.header
  l_put_be32(hdr.rollungCode,&msg.hub.down[RBF_MAC_HEADER_INDEX_ROLLUNGCODE]);    //4Bytes
  l_put_u8(hdr.frameCtl,&msg.hub.down[RBF_MAC_HEADER_INDEX_FRAMECTL]);            //1Byte


  l_put_be16(hdr.syncClock,&msg.hub.down[RBF_MAC_HEADER_INDEX_SYNCCLOCK]);        //2Bytes
  l_put_u8(hdr.hsclock,&msg.hub.down[RBF_MAC_HEADER_INDEX_HSCLOCK]);              //1Byte

  //hdr.panId(3B) + hdr.srcId(1B)
  l_put_be32(((uint32_t)hdr.panId<<8)|hdr.srcId, &msg.hub.down[RBF_MAC_HEADER_INDEX_PANDID] );     //4Byte
  l_put_u8(hdr.destID,&msg.hub.down[RBF_MAC_HEADER_INDEX_DESTID]);               //1Byte
  l_put_u8(hdr.routID,&msg.hub.down[RBF_MAC_HEADER_INDEX_ROUTID]);              //1Byte
  l_put_u8(hdr.cmd,&msg.hub.down[RBF_MAC_HEADER_INDEX_CMD]);
  //2. pack[0]
  l_put_u8(RBF_MAC_PACKET_GATEWAY_ACK_EVENT_LEN,&msg.hub.down[RBF_MAC_PACKET_LEN_INDEX]); //packet length

  //3.payload
  temp8 = 0; //get rssi
  l_put_u8(temp8,&msg.hub.down[RBFMAC_PAYLOAD_GATEWAY_ACK_EVENT_INDEX_RSSI]);//15
  temp8 = 0; //get qrfH1
  l_put_u8(temp8,&msg.hub.down[RBFMAC_PAYLOAD_GATEWAY_ACK_EVENT_INDEX_QRFH1]);//16
  temp8 = 0; //get qrfH2
  l_put_u8(temp8,&msg.hub.down[RBFMAC_PAYLOAD_GATEWAY_ACK_EVENT_INDEX_QRFH2]);//17
  temp32 = 0; //get temp32
  l_put_be32(temp32,&msg.hub.down[RBFMAC_PAYLOAD_GATEWAY_ACK_EVENT_INDEX_MAC]);
  //===
  DS_app_log_hexdump_debug("Gateway Ack event pack:",msg.hub.down,msg.hub.down[0]+1);

}
#endif// end of "HUB_DEVICE"

static bool rfm_reg_state = false;   // 正在注册标识
// 注册标志
static bool get_rfm_reg_state(void)
{
    return rfm_reg_state;
}

static void set_rfm_reg_state(void)
{
    rfm_reg_state = 1;
}

static void clean_rfm_reg_state(void)
{
    rfm_reg_state = 0;
}

#if defined (RFM_DEVICE)
void Commissiong_join_node_paging_packet(uint8_t cn)
{
  uint8_t buff[8];
  //set 注册标志
  set_rfm_reg_state();
  RBFMacMessageJoinRequest_t join_msg={
      .qrfR1 = 0x55,
      .qrfR2 = 0x66,
      .echASeq = 0x77,
      .mac = 0,
  };
  /*节点寻呼组包
   *1. RFM随机生成codeA
   *2. 取macAdd8,macAdd2
   *3. 取deviceType
   *4. TODO: (MsgSeq MsgRetry  QrfR1 QrfR2 EchASeq)等值暂未取
   */
  memset(msg.rfm.up,0,DATA_LINK_LENGTH);

  join_msg.hardType = net_get_hard_type();
  join_msg.modelType = net_get_model_type();
  join_msg.rfVer = net_get_rfVer();
  join_msg.sVer = net_get_sVer();
  join_msg.temp = SM_tempDrv_get();
  join_msg.rssi = (uint8_t)(bsp_rf_rssi_get()+128);
  join_msg.battV = SM_battery_get();

  getThisParam(ENpbyKeyM,join_msg.sn);

//  join_msg.msgSeq = get_msgSeq();
  join_msg.msgRetry = 1;

  RBF_generate_data_codeA(_key); //随机生成codeA

  memcpy(join_msg.keyCodeA,_key,RBF_KEY_LENGTH_MAX);
  DS_app_log_hexdump_debug("[RFM codeAkey]: ",join_msg.keyCodeA,RBF_KEY_LENGTH_MAX);

  getThisParam(ENpbyMacID,buff); //获取macAdd 8bytes
  join_msg.macAdd8=l_get_be64(buff);
  join_msg.macAdd2= join_msg.macAdd8&0xffff;
  join_msg.deviceType = net_get_device_type();

  DS_app_log_hexdump_error("MAC:",buff,MAC_ADDRESS_LENGTH);
  RBF_set_node_paging(join_msg,msg.rfm.up);

  DS_app_log_hexdump_debug("[node paging] up:",msg.rfm.up,msg.rfm.up[0]+1);

  //msg.status = EN_COMMISSIONG_JOIN_NODE_PAGING_NET_AE;
  msg.rfmStatus = EN_MSG_STATUS_JOIN_NODE_PAGING_BUILD_PACKET;
  clear_register_status();

  set_cmd_ack(0);
  if(cn == 0){
      join_count = 10;
  }
  else {
      join_count = cn;
  }
  setMacTransEvent(EN_TRANS_REQ_REGISTER,0x01,join_count,LBT_REDO_COUNT_MAX);
  set_b_rfm_confirm(false);
}
#endif //end of "RFM_DEVICE"
/*
 *@brief 节点入网确认组包
 */
#if defined (RFM_DEVICE)
void Commissiong_join_confirm_packet(void)
{
  uint8_t buff[8]={0};
  RBFMacMessageNodeJoinConfirm_t join_confirm_msg = {
      .msgSeq = 0x11,
      .msgRetry = 0x22,
      .qrfR1 = 0x55,
      .qrfR2 = 0x66,
      .echASeq = 0x77,
      .mac = 0,
  };
  /*1. 取MacAdd2,macAdd8,DeviceType
   *2. DOTO: (MsgSeq MsgRetry QrfR1 QrfR2 EchASeq)未取
   *
   *
   */
  memset(msg.rfm.up,0,DATA_LINK_LENGTH);
  join_confirm_msg.hardType = net_get_hard_type();
  join_confirm_msg.modelType = net_get_model_type();
  join_confirm_msg.rfVer = net_get_rfVer();
  join_confirm_msg.sVer = net_get_sVer();
  join_confirm_msg.temp = SM_tempDrv_get();
  join_confirm_msg.rssi = (uint8_t)(bsp_rf_rssi_get()+128);
  join_confirm_msg.battV = SM_battery_get();
//  join_confirm_msg.msgSeq = get_msgSeq();
  join_confirm_msg.msgRetry = 20;//0x0F;

  getThisParam(ENpbyMacID,buff); //获取macAdd 8bytes
  join_confirm_msg.macAdd8=l_get_be64(buff);
  join_confirm_msg.macAdd2= join_confirm_msg.macAdd8&0xffff;
  join_confirm_msg.deviceType = net_get_device_type();
  getThisParam(ENpbyKeyM,join_confirm_msg.sn);

  RBF_set_node_join_confirm(join_confirm_msg,msg.rfm.up);
  msg.rfmStatus = EN_MSG_STATUS_JOIN_CONFIRM_BUILD_PACKECT;
//  setMacTransEvent(EN_TRANS_REQ_REGISTER,0x01,ADHOC_RETRY_COUNT_MAX,LBT_REDO_COUNT_MAX);
}
#endif //end of "RFM_DEVICE"
void txStatecallbackCommissiong (uint8_t** ppPacket,MAC_TX_STATE_E currState,void* pData)
{
#if defined (RFM_DEVICE)
  RETRY_CTRL_ST* pRetryCtrl = (RETRY_CTRL_ST*)pData;
  uint32_t ret;
  //回调状态为组包
  if(currState == EN_MAC_TX_STATE_IDLE_PACKET_ASSEMBLE)
  {

      memcpy(msg.rfm.buff,msg.rfm.up,msg.rfm.up[0]+1);  //TODO:原数据保存，防止数据多次加密
      *ppPacket = msg.rfm.buff;//msg.rfm.up; //传入报文指针，组包
      DS_app_log_info("*T-C%d-%d-%d -%d-%d",
                      msg.rfm.buff[RBF_MAC_HEADER_INDEX_CMD],
                      get_msgSeq(),
                      msg.rfm.buff[RBF_MAC_PAYLOAD_JOIN_REQ_INDEX_MSGRETRY],
                      pRetryCtrl->byRetryCount,
                      pRetryCtrl->byRetryMaxTimes
                      );
#if defined (RFM_DEVICE)
      if(msg.rfmStatus == EN_MSG_STATUS_JOIN_CONFIRM_BUILD_PACKECT){
          msg.rfmStatus = EN_MSG_STATUS_JOIN_CONFIRM_NET_AE;
          setMacTransEvent(EN_TRANS_REQ_REGISTER,0x01,ADHOC_RETRY_COUNT_MAX,LBT_REDO_COUNT_MAX);
          if(get_net_printf_log() == true){
              DS_app_log_error("T-C-3 INIT\n");
          }
      }
#endif
      if(msg.rfm.buff[RBF_MAC_PAYLOAD_JOIN_REQ_INDEX_MSGRETRY] != pRetryCtrl->byRetryCount){

          l_put_be32(get_device_itself_rolling_code(),&msg.rfm.buff[RBF_MAC_HEADER_INDEX_ROLLUNGCODE]);
          msg.rfm.buff[RBF_MAC_PAYLOAD_JOIN_REQ_INDEX_MSGRETRY] = pRetryCtrl->byRetryCount;
          msg.rfm.buff[RBF_MAC_PAYLOAD_JOIN_REQ_INDEX_MSGSEQ] = get_msgSeq();
          DS_app_log_hexdump_debug("*tx-o-d:",msg.rfm.buff,msg.rfm.buff[0]+1);

          if(msg.rfmStatus == EN_MSG_STATUS_JOIN_NODE_PAGING_BUILD_PACKET){
              //aes-ccm
              ret=mac_payload_crypto(msg.rfm.buff);
              if(ret != 0){
                  if(get_net_printf_log() == true){
                      DS_app_log_error("E*ret=%ld\n",ret);
                  }
              }
          }
          else if(msg.rfmStatus == EN_MSG_STATUS_JOIN_CONFIRM_NET_AE){
              //aes-ccm
              ret = mac_payload_crypto(msg.rfm.buff);
              if(ret != 0){
                  DS_app_log_error("E*ret=%ld\n",ret);
              }
          }
          DS_app_log_hexdump_debug("*tx-a-d:",msg.rfm.buff,msg.rfm.buff[0]+1);
      }

  }
  if(get_net_printf_log() == true){
      DS_app_log_error("*T-S:%d",currState);
  }
  if(pData!=NULL)
  {
      DS_app_log_info("retry%d-%d",pRetryCtrl->byRetryCount,pRetryCtrl->byRetryMaxTimes);
  }
  DS_app_log_info("\r\n");

  if(currState == EN_MAC_TX_STATE_FAILED)
  {
      if(get_net_printf_log() == true){
          DS_app_log_error("***TX EN_MAC_TX_STATE_FAILED\n");
      }
      clean_rfm_reg_state();
      net_msgseq_update();
  }

  if(currState == EN_MAC_TX_STATE_SUCCED){
      if(get_net_printf_log() == true){
          DS_app_log_error("***TX EN_MAC_TX_STATE_SUCCED");
      }
      net_msgseq_update();
      if(msg.rfmStatus == EN_MSG_STATUS_JOIN_CONFIRM_BUILD_PACKECT){
          msg.rfmStatus = EN_MSG_STATUS_JOIN_CONFIRM_NET_AE;
          if(get_net_printf_log() == true){
              DS_app_log_error("***TX EN_COMMISSIONG_JOIN_CONFIRM_BUILD_PACKECT");
          }
          setMacTransEvent(EN_TRANS_REQ_REGISTER,0x01,ADHOC_RETRY_COUNT_MAX,LBT_REDO_COUNT_MAX);
          if(get_net_printf_log() == true){
              DS_app_log_error("*T-C%d pid:%02X%02X%02X sid:%02X did:%02X\n", ppPacket[RBF_MAC_HEADER_INDEX_CMD],
                   ppPacket[RBF_MAC_HEADER_INDEX_PANDID],
                   ppPacket[RBF_MAC_HEADER_INDEX_PANDID + 1],
                   ppPacket[RBF_MAC_HEADER_INDEX_PANDID + 2],
                   ppPacket[RBF_MAC_HEADER_INDEX_SRCID],
                   ppPacket[RBF_MAC_HEADER_INDEX_DESTID]);
          }
      }

  }
#else
  (void) ppPacket;
  (void) pData;
  (void) currState;
#endif //end of "RFM_DEVICE"
}


/*
 * HUB下行数据
 */
#if defined (HUB_DEVICE)
void Commissiong_gw_allow_join_net_packt(void)
{
  RBFMacHeader_t hdr;
  size_t len;
  uint8_t buf[3]={0};

  RBFMacMessageGWAlloawJoinNetwork_t gw_join_msg ={
      .macAdd4 = 0x11223344,
      .rollingCode = 0x55667788,
      .localID = 0xddee,
      .broadcastKeyCode = {0},
      .keyCodeB = {0},
      .systemKeyCode = {0},//
      .mac = 0xa55ab66b,
  };

 /*1.取macAdd4,codeB,LocalID，broadcastKeyCode,systemKeyCode
 *2.TODO:(RollingCode)未取
 * 从NVM获取CodeB,broadcastKeyCode,systemKeyCode
*/
  getThisParam(ENpbySystemID,buf);
  gw_join_msg.systemID = l_get_be24(buf);

  RBF_get_data_codeB(_key);  //获取keyCodeB
  memcpy(gw_join_msg.keyCodeB,_key,RBF_KEY_LENGTH_MAX);
  RBF_get_data_systemKeyCode(_key);//获取
  memcpy(gw_join_msg.systemKeyCode,_key,RBF_KEY_LENGTH_MAX);
  RBF_get_data_broadcastKeyCode(_key);
  memcpy(gw_join_msg.broadcastKeyCode,_key,RBF_KEY_LENGTH_MAX);

  gw_join_msg.macAdd4 = l_get_be64(msg.join_info.mac)&0xFFFFFFFF;
/* 1. HUB 先保存ABke
 * 2. systemKeyCode进行AES(codeAB)加密
 */
//1.保存CodeAB
//从协议中获取
  memcpy(_key,msg.join_info.codeA,RBF_KEY_LENGTH_MAX);
  XorDataLine(_key,gw_join_msg.keyCodeB,RBF_KEY_LENGTH_MAX);
  RBF_set_data_codeAB(_key);  //保存
  memcpy(msg.join_info.codeAB,_key,RBF_KEY_LENGTH_MAX);
  //set codeAB key_id
  RBF_get_data_codeAB(_key);
//  RBF_set_keyid_codeAB(_key);
  RBF_key_group_info_log();
  //2.systemKeyCode(AES)
  #if defined (CONFIG_COMMISSIONG_KEY_CRYPTO)
  DS_app_log_hexdump_debug("*tx-systemKeyCode[P]",gw_join_msg.systemKeyCode,RBF_KEY_LENGTH_MAX);
  RBF_aes_ae(KEY_ID_CODEAB,gw_join_msg.systemKeyCode,RBF_KEY_LENGTH_MAX,_key,RBF_KEY_LENGTH_MAX,&len);
  memcpy(gw_join_msg.systemKeyCode,_key,RBF_KEY_LENGTH_MAX);
  DS_app_log_hexdump_debug("*tx-broadcast[P]",gw_join_msg.broadcastKeyCode,RBF_KEY_LENGTH_MAX);
  RBF_aes_ae(KEY_ID_CODEAB,gw_join_msg.broadcastKeyCode,RBF_KEY_LENGTH_MAX,_key,RBF_KEY_LENGTH_MAX,&len);
  memcpy(gw_join_msg.broadcastKeyCode,_key,RBF_KEY_LENGTH_MAX);
  DS_app_log_hexdump_debug("*tx-broadcast[C]**",gw_join_msg.broadcastKeyCode,RBF_KEY_LENGTH_MAX);
  #endif
  gw_join_msg.localID = msg.join_info.rfmid;// TODO:localID = rfmID
  hdr.destID =  gw_join_msg.localID;
  gw_join_msg.rollingCode = 0;
  recv_rolling_code_init(PROVINED_INIT,msg.join_info.rfmid,0);

  DS_app_log_info("===test gw allow join start===\n");
  RBF_set_gw_allow_join_net(hdr,gw_join_msg,msg.hub.down);
  DS_app_log_hexdump_debug("[GW Allow Join] down:",msg.hub.down,msg.hub.down[0]+1);
 // msg.status = EN_COMMISSIONG_GW_ALLOW_JOIN_NET_NET_AE;


}
#endif //end of "HUB_DEVICE"

void txStatecallbackAdhocDown0 (uint8_t** ppPacket,MAC_TX_STATE_E currState,void* pData)
{
#if defined (HUB_DEVICE)
  if(get_rfm_reg_state() == true)//正在注册
  {
      *ppPacket = msg.hub.down;
      RETRY_CTRL_ST* pRetryCtrl = (RETRY_CTRL_ST*)pData;
  //    packet[2] = pRetryCtrl->byRetryCount;
  //    packet[3] = pRetryCtrl->byRetryMaxTimes;
      l_put_be32(get_device_itself_rolling_code(),&msg.hub.down[RBF_MAC_HEADER_INDEX_ROLLUNGCODE]);
      DS_app_log_debug("***Tx AdhocDown0 callback state:%d",currState);
      if(pData!=NULL)
      {
          DS_app_log_debug("retry%d-%d",pRetryCtrl->byRetryCount,pRetryCtrl->byRetryMaxTimes);
      }
      DS_app_log_debug("\r\n");
  }
  else
  {//已注册 下行回调函数
    mac_txStatecallbackAdhocDown0(ppPacket,currState,pData);
  }
#else
    (void) ppPacket;
    (void) currState;
    (void) pData;
#endif //end of "HUB_DEVICE"
}


#if defined (HUB_DEVICE)
uint8_t RX_get_node_paging_packet_parse(uint8_t *pData)
{
  RBFMacMessageJoinRequest_t join_msg;
  uint8_t macAdd8[8]={0};
  uint32_t ret;
  uint8_t ioen_lock = 0;
  uint8_t option=0;
  memcpy(msg.hub.up,pData,pData[0]+1);//TODO:先做数据测试
  //
  //DS_app_log_hexdump_debug("node paging ae data:",msg.hub.up,msg.hub.up[0]+1);
#if defined (CONFIG_AE_DE)

  ret = mac_payload_verify(msg.hub.up);

  memcpy(pData,msg.hub.up,msg.hub.up[0]+1);

#else
  ret = 0;
#endif
  if(ret != 0){
      if(get_net_printf_log() == true){
          DS_app_log_error("E*ret=%ld,cmd=%d\n",ret,msg.hub.up[RBF_MAC_HEADER_INDEX_CMD]);
      }
      return ret;  //解密失败
  }
  DS_app_log_debug("*rx-o-d: aes-ccm ret=%ld\n",ret);
  //
  DS_app_log_hexdump_debug("*rx-o-d:",msg.hub.up,msg.hub.up[0]+1);
  ret = RBF_get_node_paging_packet_parse(msg.hub.up,
                                   RBF_MAC_PACKET_LEN_SIZE+RBF_HEADER_LENGTH_MAX+RBF_MAC_PAYLOAD_JOIN_REQ_LEN,
                                   &join_msg);
  if(ret != 0){
      DS_app_log_error("E*paging packetret=%ld\r\n",ret);
      return ret;  //报文解析失败
  }

  /*HUB取deviceType,mac,codeA-->计算RfmID
   *
   * */
  //DS_app_log_hexdump_error("SN:",join_msg.sn,SN_LENGTH);

  if(memcmp_sn(join_msg.sn) == false){
      DS_app_log_hexdump_error("SN:",join_msg.sn,SN_LENGTH);
      l_put_be64(join_msg.macAdd8,macAdd8);
      //SN注册模式时。如果有回连的子设备，应该往下执行
      if(isJoinMac(macAdd8) == false){
          return 1;
      }
  }

  DS_app_log_hexdump_debug("*rx-codeA:",join_msg.keyCodeA,RBF_KEY_LENGTH_MAX);
  l_put_be64(join_msg.macAdd8,macAdd8);
  memcpy(msg.join_info.codeA,join_msg.keyCodeA,RBF_KEY_LENGTH_MAX);
  memcpy(msg.join_info.mac,macAdd8,8);
  msg.join_info.deviceType = join_msg.deviceType;
  //
  DS_app_log_info("*rx-deviceType %d\n",msg.join_info.deviceType);
  DS_app_log_hexdump_debug("node mac8:",msg.join_info.mac,8);
  //写入nvm
  //0新分配ID，1ID已存在，2ID用完分配失败，3出错

  ret = setRfmId(msg.join_info.deviceType,msg.join_info.mac,&msg.join_info.rfmid);
  DS_app_log_error("setRfmId ret:%ld\r\n",ret);
  if(ret == 2 || ret == 3){ //ID分配失败或出错
      return 1;
  }
#ifndef   CONFIG_NVM_VERSION
      setDeviceParam(msg.join_info.rfmid, ENpbyNodeSNFirst, join_msg.sn);
      setDeviceParam(msg.join_info.rfmid, ENpbyNodeDeviceTypeFirst, &join_msg.deviceType);
#endif

  if(msg.join_info.rfmid >= RFMID_EN_INDEX_IO_FIRST && msg.join_info.rfmid <= RFMID_EN_INDEX_IO_LAST){
      if(msg.join_info.deviceType == EN_DEVICE_TYPE_IO_PIR){
          ioen_lock = 60; //在定时10S的定时器里减
          setDeviceParam(msg.join_info.rfmid, ENbyIOenLock, &ioen_lock);
      }else{
          ioen_lock = 0;
          setDeviceParam(msg.join_info.rfmid, ENbyIOenLock, &ioen_lock);
      }
  }

  //if( setRfmId(msg.join_info.deviceType,msg.join_info.mac,&msg.join_info.rfmid) == 0){
  //codeAB
  RBF_get_data_codeB(_key);
  XorDataLine(_key,msg.join_info.codeA,RBF_KEY_LENGTH_MAX);
#ifndef   CONFIG_NVM_VERSION
          setNodeJoinCodeAB(_key,msg.join_info.rfmid);
#else
  if(ret == 0){ //新分配的ID，置C1，用于没收到cmd3清除记录
      setNodeRegInfo(msg.join_info.rfmid,_key,join_msg.sn,ENbyNodeRegInfoOption_C1,&join_msg.deviceType);
      DS_app_log_error("C1\r\n");
      reg_setInvaildRFMIdToRam(msg.join_info.rfmid);
  }else{
      ret = getDeviceParam(msg.join_info.rfmid,ENbyNodeDeviceOptionFirst,&option);
      if(ret != 0){
          option = ENbyNodeRegInfoOption_C1;
          DS_app_log_error("Err C1\r\n");
          reg_setInvaildRFMIdToRam(msg.join_info.rfmid);
      }else{
          //已存在的ID，保持option不变化
          setNodeRegInfo(msg.join_info.rfmid,_key,join_msg.sn,option,&join_msg.deviceType);
      }
  }
#endif
  DS_app_log_error("*tx-rfmid = %d \r\n",msg.join_info.rfmid);
  DS_app_log_hexdump_debug("Hub get codeAB:",_key,RBF_KEY_LENGTH_MAX);

  DS_app_log_hexdump_debug("parse codeAkey: ",join_msg.keyCodeA,RBF_KEY_LENGTH_MAX);
  return 0;
}

uint8_t RX_get_node_paging_packet_parse_registeredNode(uint8_t *pData)
{
  RBFMacMessageJoinRequest_t join_msg;
  uint8_t macAdd8[8]={0};
  uint32_t ret;
  uint8_t ioen_lock = 0;
  uint8_t option=0;
  memcpy(msg.hub.up,pData,pData[0]+1);

  ret = mac_payload_verify(msg.hub.up);
  memcpy(pData,msg.hub.up,msg.hub.up[0]+1);

  if(ret != 0){
      if(get_net_printf_log() == true){
          DS_app_log_error("E*ret=%ld,cmd=%d\n",ret,msg.hub.up[RBF_MAC_HEADER_INDEX_CMD]);
      }
      return ret; //解密失败
  }
  DS_app_log_debug("*rx-o-d: aes-ccm ret=%ld\n",ret);

  DS_app_log_hexdump_debug("*rx-o-d:",msg.hub.up,msg.hub.up[0]+1);
  ret = RBF_get_node_paging_packet_parse(msg.hub.up,
                                   RBF_MAC_PACKET_LEN_SIZE+RBF_HEADER_LENGTH_MAX+RBF_MAC_PAYLOAD_JOIN_REQ_LEN,
                                   &join_msg);
  if(ret != 0){
      return ret; //解析失败
  }


  /*HUB取deviceType,mac,codeA-->计算RfmID
   *
   */
  //DS_app_log_hexdump_error("SN:",join_msg.sn,SN_LENGTH);
#if 0 //非注册模式。不需要再判断一次
  if(memcmp_sn(join_msg.sn) == false){
      DS_app_log_hexdump_error("SN:",join_msg.sn,SN_LENGTH);
      return 1;
  }
#endif
  DS_app_log_hexdump_debug("*rx-codeA:",join_msg.keyCodeA,RBF_KEY_LENGTH_MAX);

  l_put_be64(join_msg.macAdd8,macAdd8);
  if(isJoinMac(macAdd8) == false){
      return 1; //没有注册过
  }
  memcpy(msg.join_info.codeA,join_msg.keyCodeA,RBF_KEY_LENGTH_MAX);
  memcpy(msg.join_info.mac,macAdd8,8);
  msg.join_info.deviceType = join_msg.deviceType;
      //
  DS_app_log_info("*rx-deviceType %d\n",msg.join_info.deviceType);
  DS_app_log_hexdump_debug("node mac8:",msg.join_info.mac,8);

  ret = isRfmIdEmpty(msg.join_info.deviceType, msg.join_info.mac, &msg.join_info.rfmid);
  if(ret != 1){
      return 1; //不存在
  }

  ret = getDeviceParam(msg.join_info.rfmid, ENbyNodeDeviceOptionFirst, &option);
  if(ret != 0  ||  option == ENbyNodeRegInfoOption_C1){
      return 1; //状态错误
  }
#ifndef   CONFIG_NVM_VERSION
      setDeviceParam(msg.join_info.rfmid, ENpbyNodeSNFirst, join_msg.sn);
      setDeviceParam(msg.join_info.rfmid, ENpbyNodeDeviceTypeFirst, &join_msg.deviceType);
#endif

  if(msg.join_info.rfmid >= RFMID_EN_INDEX_IO_FIRST && msg.join_info.rfmid <= RFMID_EN_INDEX_IO_LAST){
      if(msg.join_info.deviceType == EN_DEVICE_TYPE_IO_PIR){
          ioen_lock = 60; //在定时10S的定时器里减
          setDeviceParam(msg.join_info.rfmid, ENbyIOenLock, &ioen_lock);
      }else{
          ioen_lock = 0;
          setDeviceParam(msg.join_info.rfmid, ENbyIOenLock, &ioen_lock);
      }
  }

  //codeAB
  RBF_get_data_codeB(_key);
  XorDataLine(_key,msg.join_info.codeA,RBF_KEY_LENGTH_MAX);
#ifndef   CONFIG_NVM_VERSION
          setNodeJoinCodeAB(_key,msg.join_info.rfmid);
#else
  setNodeRegInfo(msg.join_info.rfmid,_key,join_msg.sn,ENbyNodeRegInfoOption_C3,&join_msg.deviceType);
  DS_app_log_error("C-3\r\n");
  reg_clrInvaildRFMIdToRam(msg.join_info.rfmid);//置C3,应该是清ram而不是置ram//reg_setInvaildRFMIdToRam(msg.join_info.rfmid);
#endif
  DS_app_log_debug("*tx-rfmid = %d \n",msg.join_info.rfmid);
  DS_app_log_hexdump_debug("Hub get codeAB:",_key,RBF_KEY_LENGTH_MAX);

  DS_app_log_hexdump_debug("parse codeAkey: ",join_msg.keyCodeA,RBF_KEY_LENGTH_MAX);

  return ret;
}
#endif // end of "HUB_DEVICE"
#if defined (HUB_DEVICE)
uint32_t Rx_get_node_join_confirm_packet_parse(uint8_t *pData)
{
  uint32_t ret;
  RBFMacMessageNodeJoinConfirm_t pack_msg;
  uint32_t sysId = 0;
  uint8_t rid = 0;

  sysId = (l_get_be32(pData+RBF_MAC_HEADER_INDEX_PANDID)>>8)&0xFFFFFF;//获取panID(bit31~bit8) + srcID(bit7~bit0)
  rid = l_get_u8(pData+RBF_MAC_HEADER_INDEX_SRCID);

  if(get_net_printf_log() == true){
      DS_app_log_error("RID:%02X dID:%02X PID:%06lX CD:%02X\r\n",
                       rid,
                       l_get_u8(pData+RBF_MAC_HEADER_INDEX_DESTID),
                       sysId,
                       l_get_u8(pData+RBF_MAC_HEADER_INDEX_CMD));
  }
  if(net_addressing_check_sysId(sysId) != true
      && sysId != 0xFFFFFF){
      //TODO:兼容旧的RFM设备systemID为0xFFFFFF,且老化测试网关为0xFFFFFF.
      DS_app_log_error("System ID diff\n");
      return 2; //sysid错误
  }
  if(rid == 0 || rid == 0xff){
      DS_app_log_error("R-C3 source ID:0x%02x\r\n",rid);
      return 2;
  }

  memcpy(msg.hub.down,pData,pData[0]+1);//TODO:先做数据测试
  ret = mac_payload_verify(msg.hub.down);
  if(ret != 0 ){
      if(get_net_printf_log() == true){
          DS_app_log_error("E*join confirm ret=%ld\n",ret);
      }
      return ret;
  }
  set_rfm_id(l_get_u8(pData+RBF_MAC_HEADER_INDEX_SRCID));
  memcpy(pData,msg.hub.down,msg.hub.down[0]+1);

  ret = RBF_get_node_join_confirm(msg.hub.down,RBF_MAC_PACKET_LEN_SIZE+RBF_HEADER_LENGTH_MAX+RBF_MAC_PAYLOAD_JOIN_CONFIRM_LEN,&pack_msg);
  if(ret != 0){
      return ret;
  }

  if(get_net_printf_log() == true){
      DS_app_log_error("MAC:%04X BT:%02X Ver:%06X-%06X TY:%02X HY:%02X ",
                       pack_msg.macAdd2,pack_msg.battV,pack_msg.rfVer,pack_msg.sVer,pack_msg.deviceType,pack_msg.hardType);
      DS_app_log_error("SN:%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X\n",
                       pack_msg.sn[0],pack_msg.sn[1],pack_msg.sn[2],pack_msg.sn[3],
                       pack_msg.sn[4],pack_msg.sn[5],pack_msg.sn[6],pack_msg.sn[7],
                       pack_msg.sn[8],pack_msg.sn[9],pack_msg.sn[10],pack_msg.sn[11],
                       pack_msg.sn[12],pack_msg.sn[13],pack_msg.sn[14],pack_msg.sn[15]);
  }
#if 1
  return 0;
#else
  if(pack_msg.macAdd2 != (l_get_be64(msg.join_info.mac)&0xFFFF)){
      DS_app_log_error("E* mac address is diff\n");
      ret = 1;
  }else{
      //msg.hubStatus = EN_MSG_STATUS_JOIN_CONFIRM_SUCCESS;//EN_COMMISSIONG_JOIN_CONFIRM_SUCCESS;//HUB收到注册成功，
      ret = 0;
  }
  return ret;
#endif
}
uint32_t Rx_get_node_join_confirm_packet_parse_registeredNode(uint8_t *pData)
{
  uint32_t ret;
  RBFMacMessageNodeJoinConfirm_t pack_msg;
  uint32_t sysId = 0;
  uint8_t rid = 0;

  sysId = (l_get_be32(pData+RBF_MAC_HEADER_INDEX_PANDID)>>8)&0xFFFFFF;//获取panID(bit31~bit8) + srcID(bit7~bit0)
  rid = l_get_u8(pData+RBF_MAC_HEADER_INDEX_SRCID);

  if(get_net_printf_log() == true){
      DS_app_log_error("RID:%02X dID:%02X PID:%06lX CD:%02X ",
                       rid,
                       l_get_u8(pData+RBF_MAC_HEADER_INDEX_DESTID),
                       sysId,
                       l_get_u8(pData+RBF_MAC_HEADER_INDEX_CMD));
  }
  if(net_addressing_check_sysId(sysId) != true
      && sysId != 0xFFFFFF){
      //TODO:兼容旧的RFM设备systemID为0xFFFFFF,且老化测试网关为0xFFFFFF.
      if(get_net_printf_log() == true){
          DS_app_log_error("System ID diff\n");
      }
      return 2;
  }
  if(rid == 0 || rid == 0xff){
      DS_app_log_error("R-C3 source ID:0x%02x\r\n",rid);
      return 2;
  }

  memcpy(msg.hub.down,pData,pData[0]+1);//TODO:先做数据测试
  ret = mac_payload_verify(msg.hub.down);
  if(ret != 0 ){
      if(get_net_printf_log() == true){
          DS_app_log_error("E*join confirm ret=%ld\n",ret);
      }
      return ret;
  }

  set_rfm_id(l_get_u8(pData+RBF_MAC_HEADER_INDEX_SRCID));
  memcpy(pData,msg.hub.down,msg.hub.down[0]+1);

  ret = RBF_get_node_join_confirm(msg.hub.down,RBF_MAC_PACKET_LEN_SIZE+RBF_HEADER_LENGTH_MAX+RBF_MAC_PAYLOAD_JOIN_CONFIRM_LEN,&pack_msg);
  if(ret != 0){
      return ret;
  }
#if 0 //能执行到这里，说明已经是注册过的子设备，否则解密应该会失败
  //TODO: check is resistered
  if(isJoinMac(&msg.hub.down[RBF_MAC_PAYLOAD_JOIN_CONFIRM_INDEX_MACADD8]) == false){
      return 1;
  }
#endif

  if(get_net_printf_log() == true){
      DS_app_log_error("MAC:%04X BT:%02X Ver:%06X-%06X TY:%02X HY:%02X ",
                       pack_msg.macAdd2,pack_msg.battV,pack_msg.rfVer,pack_msg.sVer,pack_msg.deviceType,pack_msg.hardType);
      DS_app_log_error("SN:%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X\n",
                       pack_msg.sn[0],pack_msg.sn[1],pack_msg.sn[2],pack_msg.sn[3],
                       pack_msg.sn[4],pack_msg.sn[5],pack_msg.sn[6],pack_msg.sn[7],
                       pack_msg.sn[8],pack_msg.sn[9],pack_msg.sn[10],pack_msg.sn[11],
                       pack_msg.sn[12],pack_msg.sn[13],pack_msg.sn[14],pack_msg.sn[15]);
  }
  return 0;
}
#endif // end of "HUB_DEVICE"
#if defined (RFM_DEVICE)
uint32_t RX_get_gw_allow_join_net_packet_parse(uint8_t *pData)
{
  RBFMacMessageGWAlloawJoinNetwork_t msg_pyd;
  RBFMacHeader_t hdr;
  uint32_t ret;
  uint8_t buf[3];
  size_t len;
  memcpy(msg.rfm.down,pData,pData[0]+1);//TODO:先做数据测试
#if defined (CONFIG_AE_DE)
  ret = mac_payload_verify(msg.rfm.down);
#else
  ret = 0;
#endif
  if(ret != 0) {
      DS_app_log_error("E*R aes-ccm fail,ret=%ld\n",ret);
      return ret;
  }
  DS_app_log_debug("*rx aes-ccm ret=%ld\n",ret);
  DS_app_log_hexdump_debug("*rx-o-d:",msg.rfm.down,msg.rfm.down[0]+1);
  ret = RBF_get_gw_allow_join_net(msg.rfm.down,RBF_MAC_PACKET_LEN_SIZE+RBF_HEADER_LENGTH_MAX+RBF_MAC_PAYLOAD_GW_ALLOW_JOIN_NETWORK_LEN);

  if(ret == 0 ){
      /*获取codeB,计算codeAB,并解密systemKey,broadcastKey
       *
       */

      RBF_header_parse(msg.rfm.down,RBF_MAC_PACKET_LEN_SIZE+RBF_HEADER_LENGTH_MAX, &hdr);
      msg.join_info.rfmid = hdr.destID;
      DS_app_log_info("*rx-rfmid = %d \n",msg.join_info.rfmid);

      RBF_gw_allow_join_net_payload_packetToMsg(msg.rfm.down,&msg_pyd);
//            DS_app_log_hexdump_debug("**broadcast[C]**",msg_pyd.broadcastKeyCode,RBF_KEY_LENGTH_MAX);

      {
      //1.RFM保存CodeAB
      RBF_get_data_codeA(_key);
      XorDataLine(_key,msg_pyd.keyCodeB,RBF_KEY_LENGTH_MAX);
      RBF_set_data_codeAB(_key);  //保存
      DS_app_log_hexdump_debug("*rx-codeAB:",_key,RBF_KEY_LENGTH_MAX);

      }

      //2.aes 解密
#if defined (CONFIG_COMMISSIONG_KEY_CRYPTO)
      //systemKeyCode
      DS_app_log_hexdump_debug("***system code(cipher)",msg_pyd.systemKeyCode,RBF_KEY_LENGTH_MAX);
      RBF_aes_de(KEY_ID_CODEAB,msg_pyd.systemKeyCode,RBF_KEY_LENGTH_MAX,_key,RBF_KEY_LENGTH_MAX,&len);
      memcpy(msg_pyd.systemKeyCode,_key,RBF_KEY_LENGTH_MAX); //copy
      DS_app_log_hexdump_debug("*rx-systemCode(plain)",msg_pyd.systemKeyCode,RBF_KEY_LENGTH_MAX);




      //broadcastkey
      DS_app_log_hexdump_debug("***broadcast code(cipher)",msg_pyd.broadcastKeyCode,RBF_KEY_LENGTH_MAX);
      RBF_aes_de(KEY_ID_CODEAB,msg_pyd.broadcastKeyCode,RBF_KEY_LENGTH_MAX,_key,RBF_KEY_LENGTH_MAX,&len);
      memcpy(msg_pyd.broadcastKeyCode,_key,RBF_KEY_LENGTH_MAX);
      DS_app_log_hexdump_debug("*rx-broadcast code(plain)",msg_pyd.broadcastKeyCode,RBF_KEY_LENGTH_MAX);


#endif

      //保存RFM
      RBF_set_data_broadcastKeyCode(msg_pyd.broadcastKeyCode);
      RBF_set_data_systemKeyCode(msg_pyd.systemKeyCode);

      l_put_be24(msg_pyd.systemID,buf);
      setThisParam(ENpbySystemID,buf);
      setThisParam(ENpbyPanId, buf);

  }
  return ret;
}
#endif // end of "RFM_DEVICE"
/*
 *
 */
static uint8_t command_ack=0;//区分应答
void set_cmd_ack(uint8_t md_ack)
{
  command_ack = md_ack;
}
void txStatecallbackAck (uint8_t **ppPacket, MAC_TX_STATE_E currState, void *pData)
{
  RETRY_CTRL_ST* pRetryCtrl = (RETRY_CTRL_ST*)pData;
  uint32_t ret;
  //回调状态为组包
  if(currState == EN_MAC_TX_STATE_IDLE_PACKET_ASSEMBLE)
  {
#if defined (HUB_DEVICE)
  if(command_ack == 0){

        if(msg.hubStatus == EN_MSG_STATUS_GW_ALLOW_JOIN_NET_BUILD_PACKET){
            Commissiong_gw_allow_join_net_packt();
        }
        else if(msg.hubStatus == EN_MSG_STATUS_JOIN_CONFIRM_BUILD_PACKECT){
            gateway_ack_event_packet();
            msg.hubStatus = EN_MSG_STATUS_JOIN_CONFIRM_SUCCESS;
        }
        DS_app_log_info("*T-C%d,L=%d\n",msg.hub.down[RBF_MAC_HEADER_INDEX_CMD],msg.hub.down[0]);
        memcpy(msg.hub.buff,msg.hub.down,msg.hub.down[0]+1);
        *ppPacket = msg.hub.buff; //传入报文指针，组包 msg.hub.down
       // msg.hub.down[RBF_MAC_PAYLOAD_JOIN_REQ_INDEX_MSGRETRY] = pRetryCtrl->byRetryCount;
        l_put_be32(get_device_itself_rolling_code(),&msg.hub.buff[RBF_MAC_HEADER_INDEX_ROLLUNGCODE]);
        DS_app_log_hexdump_debug("*tx-o-d:",msg.hub.buff,msg.hub.buff[0]+1);
  #if defined (CONFIG_AE_DE)
        ret = mac_payload_crypto(msg.hub.buff);
        if(ret!=0){
            if(get_net_printf_log() == true){
                DS_app_log_error("E*aes-ccm ret=%ld\n",ret);
            }
        }
        DS_app_log_hexdump_debug("*tx-a-d:",msg.hub.buff,msg.hub.buff[0]+1);
  #endif
  }
  else
      mac_txStatecallbackAck(ppPacket,currState,pData);
#endif //end of "HUB_DEVICE"
#ifdef RFM_DEVICE
  mac_txStatecallbackAck(ppPacket,currState,pData);
#endif
  }
  if(get_net_printf_log() == true){
      DS_app_log_error("*T-S:%d\n",currState);
  }
}

void RxCallback(RF_PACKET_ST* pPacket,MAC_RX_STATE_E currState,void* pData)
{
  uint8_t* pPacketData = NULL;
#if defined (HUB_DEVICE)
  uint8_t local_reg = 0;
#endif
  bool mac_RxCallback_ret = false;// true:不打印R-C

  if(currState == EN_RX_STATE_RX_SUCCED)
  {
    pPacketData = pPacket->start_of_packet;
    /*DS_app_log_error("*R-C%d pid:%02X%02X%02X sid:%02X did:%02X\n", pPacketData[RBF_MAC_HEADER_INDEX_CMD],
                     pPacketData[RBF_MAC_HEADER_INDEX_PANDID],
                     pPacketData[RBF_MAC_HEADER_INDEX_PANDID + 1],
                     pPacketData[RBF_MAC_HEADER_INDEX_PANDID + 2],
                     pPacketData[RBF_MAC_HEADER_INDEX_SRCID],
                     pPacketData[RBF_MAC_HEADER_INDEX_DESTID]);
                     */
    //DS_app_log_hexdump_debug("*rx-d-d:",pPacketData,pPacketData[0]+1);
#if defined (RFM_DEVICE)
    //收到应答
    if(pPacketData[RBF_MAC_HEADER_INDEX_CMD] == RBF_CMD_GATEWAY_ALLOW_JOIN_NETWORK){
        DS_app_log_debug("***RX CMD[%d]\n",pPacketData[RBF_MAC_HEADER_INDEX_CMD]);
        if(RX_get_gw_allow_join_net_packet_parse(pPacketData) == 0){
            DS_app_log_hexdump_debug("*rx-o-d:",pPacketData,pPacketData[0]+1);
            setMacTxStateEvent(EN_MAC_TX_EVENT_TYPE_WAIT_ACK_DONE,true);
            itself_rolling_code_init(PROVINED_INIT,0);
            recv_rolling_code_init(PROVINED_INIT, 0, 0);
          // ToDo 地址校验、解密成功后 做时间同步
            Commissiong_join_confirm_packet();
            set_b_rfm_confirm(true);
        }
        else {
            DS_app_log_error("E*R-C=%d\n",pPacketData[RBF_MAC_HEADER_INDEX_CMD]);
        }



    }
    else 
    {
      if( get_rfm_reg_state() && EN_TRANS_REQ_REGISTER == getMacTxStateHandlingEventType()
          && get_b_rfm_confirm() == true
          && !isTxStateRfIdle()
      ){
          //校验 set_b_rfm_confirm
      if(pPacketData[RBF_MAC_HEADER_INDEX_CMD] == RBF_CMD_GATEWAY_ACK_EVENT
          && net_unpack_ack(pPacketData,pPacketData[0])== true){
        setMacTxStateEvent(EN_MAC_TX_EVENT_TYPE_WAIT_ACK_DONE,true);
        DS_app_log_info("Mac tx ack done.-%d\n",msg.rfmStatus);
        if(msg.rfmStatus == EN_MSG_STATUS_JOIN_CONFIRM_NET_AE){
            //RFM收到网关应答
            DS_app_log_error("Node REGISTER ok.\n");
            check_logout();

#ifndef SPVN_DISABLE
            spvnSlotInit();
            startSpvnTimer(1); // 开启心跳，默认5min
#endif

#ifndef IS_JOIN_CONFIRM_SUCCESS_AUTO_SPVN_DISABLE
            setMacTransEvent(EN_TRANS_REQ_SPVN, 0x00, ADHOC_RETRY_COUNT_MAX, LBT_REDO_COUNT_MAX);
#endif
            msg.rfmStatus = EN_MSG_STATUS_JOIN_CONFIRM_SUCCESS;
            set_register_status(EN_MSG_STATUS_JOIN_CONFIRM_SUCCESS);
            clean_rfm_reg_state();
            set_b_rfm_confirm(false);
        }
      }
      }
      else
        mac_RxCallback_ret = mac_RxCallback(pPacket,  currState,  pData);
    }

#endif

#if defined (HUB_DEVICE)
    //收到应答
    getThisParam(ENbyLocalRegister,&local_reg);
    if(pPacketData[RBF_MAC_HEADER_INDEX_CMD] == RBF_CMD_NODE_PAGING && local_reg == 1){
        if(is_rssi_limit(pPacket->details.rssi) == true){
            if( RX_get_node_paging_packet_parse(pPacketData) == 0){
                DS_app_log_hexdump_debug("*rx-o-d:",pPacketData,pPacketData[0]+1);
                setMacTransEvent(EN_TRANS_REQ_ADHOC_SPVN_ACK,0x01,0,0);//应答之

                msg.hubStatus = EN_MSG_STATUS_GW_ALLOW_JOIN_NET_BUILD_PACKET;
                set_cmd_ack(0);
                set_net_data_status(NET_DATA_STATUS_SUCCESS);
            }else{
                set_net_data_status(NET_DATA_STATUS_FAIL);
            }
        }else{
            set_net_data_status(NET_DATA_STATUS_FAIL);
        }
    }
#ifdef CONFIG_REGISTERED_NODE_REG_PERMISSION_ALL
    else if(pPacketData[RBF_MAC_HEADER_INDEX_CMD] == RBF_CMD_NODE_PAGING && local_reg != 1){
        if(is_rssi_limit(pPacket->details.rssi) == true){
            if( RX_get_node_paging_packet_parse_registeredNode(pPacketData) == 0){
                DS_app_log_hexdump_debug("*rx-o-d:",pPacketData,pPacketData[0]+1);
                setMacTransEvent(EN_TRANS_REQ_ADHOC_SPVN_ACK,0x01,0,0);//应答之

                msg.hubStatus = EN_MSG_STATUS_GW_ALLOW_JOIN_NET_BUILD_PACKET;
                set_cmd_ack(0);
                set_net_data_status(NET_DATA_STATUS_SUCCESS);
            }else{
                set_net_data_status(NET_DATA_STATUS_FAIL);
            }
        }else{
            set_net_data_status(NET_DATA_STATUS_FAIL);
        }
    }
#endif
    else if(pPacketData[RBF_MAC_HEADER_INDEX_CMD] == RBF_CMD_NODE_JOIN_CONFIRM && local_reg == 1){
        if(is_rssi_limit(pPacket->details.rssi) == true){
            if(Rx_get_node_join_confirm_packet_parse(pPacketData) == 0 ){
  #if 0
              //TODO: 解决子设备SN[0]为0
              pPacketData[RBF_MAC_PAYLOAD_JOIN_CONFIRM_INDEX_SN]='D';
  #endif

#ifdef CONFIG_NVM_VERSION
              //设置option为ENbyNodeRegInfoOption_C3

//                  DS_app_log_error("R-C3 source ID:0x%d, change option C3\n",pPacketData[RBF_MAC_HEADER_INDEX_SRCID]);
              uint8_t _regInfoOption=0;
              _regInfoOption = ENbyNodeRegInfoOption_C3;
              setDeviceParam(pPacketData[RBF_MAC_HEADER_INDEX_SRCID], ENbyNodeDeviceOptionFirst,&_regInfoOption);
              DS_app_log_error("C3\r\n");
              reg_clrInvaildRFMIdToRam(pPacketData[RBF_MAC_HEADER_INDEX_SRCID]);
#endif
              DS_app_log_hexdump_debug("*rx-o-d:",pPacketData,pPacketData[0]+1);
              setMacTransEvent(EN_TRANS_REQ_ADHOC_SPVN_ACK,0x01,0,0);

              msg.hubStatus = EN_MSG_STATUS_JOIN_CONFIRM_BUILD_PACKECT;
              set_cmd_ack(0);
              set_net_data_status(NET_DATA_STATUS_SUCCESS);
          }else{
              set_net_data_status(NET_DATA_STATUS_FAIL);
          }
        }else{
            set_net_data_status(NET_DATA_STATUS_FAIL);
        }
    }
#ifdef CONFIG_REGISTERED_NODE_REG_PERMISSION_ALL
    else if(pPacketData[RBF_MAC_HEADER_INDEX_CMD] == RBF_CMD_NODE_JOIN_CONFIRM && local_reg != 1){
        if(is_rssi_limit(pPacket->details.rssi) == true){
            if(Rx_get_node_join_confirm_packet_parse_registeredNode(pPacketData) == 0 ){
#ifdef CONFIG_NVM_VERSION
                //设置option为ENbyNodeRegInfoOption_C3

    //                  DS_app_log_error("R-C3 source ID:0x%d, change option C3\n",pPacketData[RBF_MAC_HEADER_INDEX_SRCID]);
                uint8_t _regInfoOption=0;
                _regInfoOption = ENbyNodeRegInfoOption_C3;
                setDeviceParam(pPacketData[RBF_MAC_HEADER_INDEX_SRCID], ENbyNodeDeviceOptionFirst,&_regInfoOption);
                DS_app_log_error("C&3\r\n");
                reg_clrInvaildRFMIdToRam(pPacketData[RBF_MAC_HEADER_INDEX_SRCID]);
#endif
                DS_app_log_hexdump_debug("*rx-o-d:",pPacketData,pPacketData[0]+1);
                setMacTransEvent(EN_TRANS_REQ_ADHOC_SPVN_ACK,0x01,0,0);

                msg.hubStatus = EN_MSG_STATUS_JOIN_CONFIRM_BUILD_PACKECT;
                set_cmd_ack(0);
                set_net_data_status(NET_DATA_STATUS_SUCCESS);
            }else{
                set_net_data_status(NET_DATA_STATUS_FAIL);
            }
        }else{
            set_net_data_status(NET_DATA_STATUS_FAIL);
        }
    }
#endif
    else {
        mac_RxCallback_ret = mac_RxCallback(pPacket,  currState,  pData);
    }
    if(get_net_data_status()==NET_DATA_STATUS_SUCCESS)
      net_to_hub_event(pPacketData,pPacket->packet_size);
#endif
    if(mac_RxCallback_ret == false)
    {
      DS_app_log_hexdump_debug("[rx] :",pPacketData,pPacketData[0]+1);
      if(get_net_printf_log() == true){
          DS_app_log_error("*R-C%d pid:%02X%02X%02X sid:%02X did:%02X\n", pPacketData[RBF_MAC_HEADER_INDEX_CMD],
                      pPacketData[RBF_MAC_HEADER_INDEX_PANDID],
                      pPacketData[RBF_MAC_HEADER_INDEX_PANDID + 1],
                      pPacketData[RBF_MAC_HEADER_INDEX_PANDID + 2],
                      pPacketData[RBF_MAC_HEADER_INDEX_SRCID],
                      pPacketData[RBF_MAC_HEADER_INDEX_DESTID]);
      }
    }
  }
}


void netKeyInit(void)
{
  uint8_t buf[NODE_JOIN_INFO_LENGTH];


/*
 * 公共key,后期该key由生产烧录
 */
#if defined (DEBUG_MODE_KEY)
  RBF_set_data_defaultKey1(_keydefault1);
  RBF_set_data_defaultKey2(_keydefault2);
#endif

/*
 * RFM设备使用的key
 */
#if defined (RFM_DEVICE)
  //RFM
  //1.CodeA每次入网重新生成一次,初始化不进行设置
  //codeAB debug
  //RBF_set_data_codeAB(_keydefault2);
#endif //end of "RFM_DEVICE"


  /*
   * HUB设备使用的key
   */
#if defined (HUB_DEVICE)
#if defined (DEBUG_MODE_KEY)
  //TODO:自动生成broadcast key和system key.
  if( getThisParam(ENpbyBroadcastKey,_key) != 0) {

      RBF_generate_data_key(_key);
      RBF_set_data_systemKeyCode(_key);
      RBF_set_data_broadcastKeyCode(_key);
#if(0)
      DS_app_log_hexdump_error("gen broadcast key:",_key,KEY_MAX_LENGTH);
#endif
  }
//TODO:废弃程序默认的key
//  RBF_set_data_systemKeyCode(_keysystem);
//  RBF_set_data_broadcastKeyCode(_keybroadcast);
#endif

  //HUB INFO
  set_node_join_info_src_nvm();
  if(getThisParam(ENbyNodeJoinInfo,buf) != 0){
      //为出厂状态时,自动生成CodeB,并清空节点数据
      DS_app_log_info("HUB join data init ...\n");
      clearNodeJoinCount();
      DS_app_log_info("join count=%d",getNodeJoinCount());
      RBF_generate_data_codeB(_key);

      //systemID
#if defined (DEBUG_MODE_KEY)
      //TODO:测试模式,systemID自动生成
      if(getThisParam(ENpbySystemID,buf) != 0){
          buf[0] = (getMacAdd4()>>16)&0xFF;
          buf[1] = (getMacAdd4()>>8)&0xFF;
          buf[2] = getMacAdd4()&0xFF;
          setThisParam(ENpbySystemID,buf);
          DS_app_log_error("system ID:0x%02x%02x%02x\n",buf[0],buf[1],buf[2]);

          //setThisParam(ENpbyPanId,buf);
      }

#endif

  }

  //test get panid
//  if( getThisParam(ENpbyPanId, buf) == 0 ){
//      DS_app_log_error("PAN id=0x%02x%02x%02x\n",buf[0],buf[1],buf[2]);
//  }
#endif //end of "HUB_DEVICE"

}
